<template>
	<view class="main u-font-26">
		<scroll-view :style="{ height: height + 'px'}" scroll-y="true" :scroll-with-animation="true"
                   :enable-back-to-top="true">
			<view class="head-box">
				<text class="head-info">基础使用</text>
				<view class="from-box">
					<u--form labelPosition="left" ref="form1">
						<u-form-item label="分账场地" label-width="100" :labelStyle="labelStyle" borderBottom ref="item1">
							<view style="margin-bottom: 20rpx;" v-for="(item,index) in checkedMerchantStoreIdArray"
								:key="index">
								<view class="text-list-item-a">{{item.storeName}}</view>
							</view>
						</u-form-item>
            <u-form-item label="按分成比例分摊支付手续费" label-width="200" borderBottom ref="item1">
              <view style="display: flex;align-items: flex-end;justify-content: flex-end;">
                <u-switch  v-model="splitCommission"> </u-switch>
              </view>
            </u-form-item>
            <u-form-item borderBottom>
              <view class="u-flex u-row-between">
                <view style="font-size: 30rpx">指定商品分账</view>
                <u-switch  v-model="designatedGoods"> </u-switch>
              </view>
              <view v-if="designatedGoods">
                <view class="u-m-t-50 u-m-b-50">
                  <u-radio-group v-model="designatedGoodsType">
                    <u-radio activeColor="#6072FF" label="部分商品" :name="1"></u-radio>
                    <u-radio :customStyle="{marginLeft: '40rpx'}" activeColor="#6072FF" label="全部商品" :name="2"></u-radio>
                  </u-radio-group>
                </view>
                <u-button v-if="designatedGoodsType == 1" :text="btnTitle" :customStyle="goodeBtnCustomStyle" @click="navGoode()"></u-button>
              </view>
            </u-form-item>
            <u-form-item v-if="designatedGoods" borderBottom>
              <view class="u-flex u-row-between">
                <view style="font-size: 30rpx">去除成本后再进行分账<text @click="ruleModel" class="u-p-l-50" style="color: rgb(96,114,255)">规则</text></view>
                <u-switch  v-model="removalCost"></u-switch>
              </view>
            </u-form-item>
						<u-form-item label="分账类型" label-width="100" borderBottom ref="item1">
							<view class="text-list-item">在线支付收益</view>
						</u-form-item>
						<u-form-item label="分账方式" label-width="100" ref="item1">
							<view class="text-list-item">自动提现到银行卡</view>
						</u-form-item>
					</u--form>
				</view>
				<view class="info-box">
					<view class="head-box-a">
						<text class="head-info">分账商户信息</text>
						<text class="head-right-a" v-if="list.length-1 != options2.length && options2.length >0" @click="checkAccount()">选择分账商户</text>
					</view>
					<view class="body-content" v-if="list.length>0" v-for="(item,index) in list" :key="index">
						<u-row>
							<u-col span="4">
								<view class="list-text">
									<view class="list-cion"></view>
									<view style="margin-left: 10rpx;">{{item.name?item.name:''}}</view>
								</view>
							</u-col>
							<u-col span="4">
								<view>{{item.mobile?item.mobile:''}}</view>
							</u-col>
							<u-col span="3">
								<view v-if="index == 0">
									{{item.shareRate?item.shareRate:''}}%
								</view>
								<view v-else style="color: #6072FF;" @click="shareRateClick(item)">
									{{item.shareRate?item.shareRate:''}}%
								</view>
							</u-col>
							<u-col span="3" @click="delAccountModel(item,index)">
								<view v-if="index != 0">
									<u-icon name="close" color="#ff0000" size="18"></u-icon>
								</view>
							</u-col>
						</u-row>
					</view>
				</view>

				<u-popup :show="show" :round="10" closeable :closeOnClickOverlay="true" :safeAreaInsetBottom="false"
					mode="center" @close="accountClose">
					<view class="popup-view">
						<view class="popup-title">
							选择分账商户
						</view>
						<u--form labelPosition="left" ref="form1">

							<u-form-item label="分账账户" label-width="100" borderBottom ref="item1">
								<uDropdown ref="uDropdown" v-if="!showAddorEdit">
									<uDropdownItem v-model="value1" :title="accountName?accountName:options1[0].label"
										:options="options1" @change="accountChange">
									</uDropdownItem>
								</uDropdown>
								<view v-if="showAddorEdit">{{subLedger.name}}</view>
							</u-form-item>
							<u-form-item label="分账比例" label-width="100" ref="item1">
								<view style="display: flex;align-items: center;">
									<view class="number-box">
										<view class="bt" @click="btn('minus')" :class="shareRate == 0.01?'bgg':'bg'">
											<u-icon name="minus" size="14"></u-icon>
										</view>
										<view class="input-sytle">
											<u--input type="digit" inputAlign="center" @blur="inputBlur"
												@input="checkNum" v-model="shareRate" maxlength="5"></u--input>
										</view>
										<view class="bt" @click="btn('plus')" :class="shareRate == 30?'bgg':'bg'">
											<u-icon name="plus" size="14"></u-icon>
										</view>
									</view>
									<text class="icon">%</text>
								</view>
							</u-form-item>
						</u--form>
						<view class="footer-btn">
							<u-button text="取消" shape="circle" @click="accountClose()"></u-button>
							<u-button v-if="!showAddorEdit" type="primary" shape="circle" text="确定"
								@click="accountConfirm()"></u-button>
							<u-button v-if="showAddorEdit" type="primary" shape="circle" text="修改"
								@click="accountConfirmEdit()"></u-button>
						</view>
					</view>
				</u-popup>
				<u-modal :show="showModal" :content="content" @cancel="showModal=false" showCancelButton="true"
					@confirm="delAccount"></u-modal>
			</view>
		</scroll-view>
		<view class="bnt" id="bnt">
			<u-button text="保存" :customStyle="nextStepBtnCustomStyle" @click="preserveModul()"></u-button>
		</view>
    <u-popup :show="rulePopup" mode="center" round="20rpx" :customStyle="{width:'600rpx'}" :safeAreaInsetBottom="false">
      <view class="u-p-50 free-popup">
        <view style="line-height: 50rpx">
          <view>规则：</view>
          <view>分账前先扣除成本后再进行分账。</view>
          <view>分成方：(订单金额-商品成本) * 分成比例，</view>
          <view>主账号：商品成本 + (订单金额-商品成本) * 分成比例</view>
          <view class="u-m-t-30">例如：</view>
          <view>订单金额100元，成本50元。</view>
          <view>主账号、分成方的分成比例分别是60%、40%，</view>
          <view>分成方：(100 - 50) * 0.4 = 20元</view>
          <view>主账号：50 + (100 - 50) * 0.6= 80元</view>
        </view>
        <view class="u-m-t-50">
          <u-button text="我已知悉" color="#6072FF" shape="circle"
                    :customStyle="{height: '80rpx',width: '380rpx'}" @click="rulePopup=false" :safeAreaInsetBottom="false"/>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
	import {
		Decimal
	} from 'decimal.js';
	export default {
		data() {
			return {
				checkedMerchantStoreIdArray: [],
				nextStepBtnCustomStyle: {
					width: '688rpx',
					height: '88rpx',
					background: 'rgb(69, 111, 255)',
					borderRadius: '120px',
					color: '#fff',
				},
				qualificationTypeEnum: this.$qualificationTypeEnum,
				show: false,
				showAddorEdit: false,
				showedit: false,
				showModal: false,
				options1: [],
				options2: [],
				value1: 1,
				name: '',
				accountName: '',
				list: [],
				storeNameList: [],
				merchantStore: {},
				data: {},
				content: '',
				shareRate: 0.01,
				account: {
					value: 1,
					type: 0,
					merchantId: 0,
					label: '',
					ledgerMerchantRecordId: 0
				},
				indeList: -1,
				//分账商户信息
				subLedger: {},
				height:0,
				maximumRatio:'',
        goodeBtnCustomStyle:{
          width: '300rpx',
          height: '88rpx',
          background: 'rgb(69, 111, 255)',
          borderRadius: '120px',
          color: '#fff',
          marginBottom:'20rpx'
        },
        checkboxCommodityIdArray:[],
        btnTitle:'已选0件商品',
        splitCommission:true,
        designatedGoods:false,
        removalCost:false,
        designatedGoodsType:2,
        rulePopup:false,
			}
		},
		onLoad(option) {
			this.checkedMerchantStoreIdArray = JSON.parse(option.checkedMerchantStoreIdArray);
			this.maximumRatio = option.maximumRatio
			this.findQualificationByType()
		},
		onReady() {
		  this.getPomHeight();
		},
    watch: {
      'checkboxCommodityIdArray': {
        handler(newVal, oldVal) {
          if (newVal) {
            this.checkboxCommodityIdArray = newVal
            this.btnTitle = '已选'+this.checkboxCommodityIdArray.length+'件商品';
            console.log(this.checkboxCommodityIdArray,'checkboxCommodityIdArray')
          }
        },
        deep: true, // 开启对象深度监听
      },
    },
		methods: {
      ruleModel(){
        this.rulePopup = true
      },
      navGoode(){
        uni.navigateTo({
          url:'/pages-other/goods/goods?ledger='+1+'&checkboxCommodityIdArray='+this.checkboxCommodityIdArray
        })
      },
			//输入框
			checkNum(e) {
				console.log(e)
				let val = e + "";
				let min = 0.01
				let max = Number(this.maximumRatio) 
				if (!val) {
					return;
				}
				this.$nextTick(() => {
					this.shareRate = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
				})
				
				if (e > max) {
					this.$nextTick(() => {
						this.shareRate = max
					})
				}
			},
			//防止 .xxx 和空
			inputBlur(e){
				let min = 0.01
				let val = e+"";
				if(val.charAt(val.length - 1) === "." || val.charAt(0) === "."){
					this.$nextTick(() => {
						this.shareRate = min
					});
				}
				let sum = 0;
				for(let i = 0; i<val.length;i++){
					if(val[i].includes(".")){
						sum++
					}
				}
				if(sum >1 || e < min || val == ""){
					this.shareRate = min
				}else{
					this.shareRate = val
				}
			},
			//加减按钮
			btn(type) {
				let min = 0.01
				let max = Number(this.maximumRatio)
				if (type == 'plus') {
					this.shareRate = Number(new Decimal(this.shareRate).add(new Decimal(min)));
					if (this.shareRate > max) {
						this.$nextTick(() => {
							this.shareRate = max
						});
					}
				} else if (type == 'minus') {
					this.shareRate = Number(new Decimal(this.shareRate).sub(new Decimal(min)));
					if (this.shareRate < min) {
						this.$nextTick(() => {
							this.shareRate = min
						});
					}
				}
			},
			//显示弹框
			checkAccount() {
				this.show = true
				this.showAddorEdit = false
			},
			//选择分账人
			accountChange(e) {
				this.account = e
				this.accountName = e.label;
			},
			//确定分账
			accountConfirm() {
				let params = {
					id: this.account.value,
					type: this.account.qualificationType,
					merchantId: this.account.merchantId,
					shareRate: this.shareRate,
					merchantStoreId: this.merchantStore.id,
					name: this.account.label,
				}
				if (this.list.length > 0) {
					//防止重复添加分账
					let flog = this.list.some(item => item.qualificationId === params.id || item.id === params.id)
					if (!flog) {
						let total = 0;
						for (let i = 0; i < this.list.length; i++) {
							if (i != 0) {
								total = new Decimal(this.list[i].shareRate).add(new Decimal(total))
							}
						}
						let totalFie = Number(new Decimal(total).add(params.shareRate))
						if (totalFie > this.maximumRatio) {
							this.$helpers.toast('分账商户比例累加不超过渠道最大比例'+this.maximumRatio+'%');
							return
						}
						this.list.push(params)
						//添加完分账，算分账率
						this.list.map((item, index) => {
							if (index == 0) {
								item.shareRate = new Decimal(item.shareRate).sub(new Decimal(params.shareRate))
							}
						})
						//去除下拉框分账户
						for(let i=0; i< this.options1.length; i++){
							if(this.options1[i].value == params.id){
								this.options1.splice(i, 1);
								break;
							}
						}
						if(this.options1.length >0){
							this.accountName = this.options1[0].label
							this.account = this.options1[0]
						}
						this.show = false
					} else {
						this.$helpers.toast('不能重复添加');
					}
				} else {
					this.list.push(params)
					this.addMasterQualification();
					this.options1 = []
					this.options2.map(item => {
						if(item.value != params.id){
							this.options1.push(item)
						}
					})
					if(this.options1.length >0){
						this.accountName = this.options1[0].label
						this.account = this.options1[0]
					}
					this.show = false
				}
			},
			//添加主资质
			addMasterQualification() {
				if (this.list.length == 1) {
					this.$api('qualification.findQualificationByType', {
							type: this.qualificationTypeEnum.MAIN_QUALIFICATIONS
						})
						.then(res => {
							let share = new Decimal(100)
							if (res.status == 0) {
								this.list.map(item => {
									share = new Decimal(share).sub(new Decimal(item.shareRate))
								})
								let pam = {
									id: res.data[0].id,
									name: res.data[0].qualificationName,
									merchantId: res.data[0].merchantId,
									type: res.data[0].qualificationType,
									shareRate: share,
								}
								this.list.unshift(pam)
							} else {
								this.$helpers.toast('请求数据失败:' + res.data.msg);
							}
						})
				}
			},
			//查询分账人
			findQualificationByType() {
				this.options1 = []
				this.$api('qualification.findQualificationByType', {
						type: this.qualificationTypeEnum.COOPERATION_QUALIFICATION
					})
					.then(res => {
						if (res.status == 0) {
							res.data.forEach((item, index) => {
								let param = {
									value: item.id,
									label: item.qualificationName,
									merchantId: item.merchantId,
									qualificationType: item.qualificationType,
								}
								if (index == 0) {
									this.account = param
								}
								this.options1.push(param)
								this.options2 = this.options1
							})
						} else {
							this.$helpers.toast('请求数据失败:' + res.data.msg);
						}
					})
			},
			//点击某一个分账
			shareRateClick(item) {
				this.show = true
				this.showAddorEdit = true
				this.shareRate = item.shareRate
				this.subLedger = item
			},
			//修改分账率
			accountConfirmEdit() {
				//算 除主分账外，累加不超过百分30
				let total = 0;
				for (let i = 0; i < this.list.length; i++) {
					if (i != 0 && this.list[i].id != this.subLedger.id) {
						total = new Decimal(this.list[i].shareRate).add(new Decimal(total))
					}
				}
				let totalFie = Number(new Decimal(this.shareRate).add(new Decimal(total)))
				if (totalFie > this.maximumRatio) {
					this.$helpers.toast('分账商户比例累加不超过渠道最大比例'+this.maximumRatio+'%');
					return
				}

				//减主资质分帐率
				let newShareRate = new Decimal(this.shareRate).sub(new Decimal(this.subLedger.shareRate))
				for (let i = 0; i < this.list.length; i++) {
					if (this.list[i].id == this.subLedger.id) {
						this.list[i].shareRate = this.shareRate
					}
				}
				//减主商户
				this.list[0].shareRate = new Decimal(this.list[0].shareRate).sub(new Decimal(newShareRate))
				this.show = false
			},
			//删除分账人弹框
			delAccountModel(item, index) {
				this.subLedger = item
				this.content = '确定移除【' + item.name + '】分账吗？'
				this.showModal = true
				this.indeList = index
			},
			//移除分账
			delAccount() {
				for (let i = 0; i < this.list.length; i++) {
					if (this.indeList == i) {
						this.list[0].shareRate = new Decimal(this.list[0].shareRate).add(Decimal(this.list[i].shareRate))
					}
				}
				//根据下标删除分账商户数据
				this.list.splice(this.indeList, 1);
				
				//分账人添加到下拉框
				let param = {
					value: this.subLedger.id,
					label: this.subLedger.name,
					merchantId: this.subLedger.merchantId,
					qualificationType: this.subLedger.type,
				}
				if(this.options1.length == 0){
					this.options1.push(param)
				}else{
					let flog = this.options1.some(item => item.value === param.value)
					if(!flog){
						this.options1.push(param)
					}
				}
				this.accountName = this.options1[0].label
				this.account = this.options1[0]
				this.showModal = false
			},
			//关闭弹框
			accountClose() {
				this.show = false
			},
			//保存数据弹框
			preserveModul(){
				if(this.options2.length == 0){
					this.$helpers.toast('没有分账商户');
					return;
				}
				let _this = this
				uni.showModal({
					title: '确定保存数据吗？',
					cancelText: '取消',
					confirmText: '确认',
					showCancel: true,
					success(res) {
						if (res.confirm) {
							//调起扫码
							_this.preserve();
						}else{
							uni.navigateBack({
								delta: 1
							});
						}
					}
				});
			},
			//保存数据
			preserve() {
        if(this.designatedGoodsType == 1 && this.checkboxCommodityIdArray.length <= 0){
          this.$helpers.toast('请选择商品');
          return;
        }
				if (this.list.length <= 1) {
					this.$helpers.toast('请选择分账');
					return;
				}
				let merchantStoreIdArray = []
				this.checkedMerchantStoreIdArray.map(item => {
					merchantStoreIdArray.push(item.merchantStoreId)
				})
				let params = {
					merchantStoreIdArray: merchantStoreIdArray,
					ledgerMerchantRecordList: this.list,
          splitCommission:this.splitCommission,
          designatedGoods:this.designatedGoods,
          removalCost:this.removalCost,
          designatedGoodsType:this.designatedGoodsType,
          checkboxCommodityIdArray:this.checkboxCommodityIdArray,
				}
				this.$api('ledgerMerchantRecord.editLedgerMerchantOrRecordBatch', params)
					.then(res => {
						if (res.status == 0) {
							this.$helpers.toast('保存成功');
							setTimeout(()=>{
								uni.navigateBack({
									delta: 1
								});
							},700)
						} else {
							this.$helpers.toast('请求数据失败:' + res.data.msg);
						}
					})
			},
			//计算滚动条高度
			getPomHeight() {
			  let query = wx.createSelectorQuery().in(this)
			  query.select('#bnt').boundingClientRect()
			  query.exec(res => {
			    this.height = wx.getSystemInfoSync().windowHeight - 32;
			    for (let i = 0; i < res.length; i++) {
			      this.height -= res[i].height;
			    }
			  });
			},
		}
	}
</script>

<style lang="scss" scoped>
	/deep/ .u-input {
		background-color: #EBECEE;
		padding: 2rpx 9rpx !important;
	}
  /deep/ .u-radio-group{
    display: flex !important;
    justify-content: center !important;
  }

	.main {
		.head-info {
			font-size: $f-lg;
		}

		.head-box {
			padding: 20rpx 20rpx 0 20rpx;
			background-color: #fff;

			.from-box {
				margin-top: 40rpx;
				color: rgba(0, 0, 0, 0.7);

				.text-list-item-a {
					margin-top: 20rpx;
				}

				.text-list-item {
					margin: 20rpx 0;
				}


			}
		}

		.list-cion {
			width: 5px;
			height: 5px;
			background: rgb(96,114,255);
			border-radius: 50%;
		}

		.bnt {
			position: fixed;
			bottom: 0;
			width: 100%;
			background-color: white;
			padding: 30rpx 0rpx;
		}

		.info-box {
			margin-top: 30rpx;
			padding: 20rpx;
			background-color: #fff;

			.head-box-a {
				display: flex;
				justify-content: space-between;
				width: 100%;

				.head-right-a {
					font-size: $f-base;
					color: $u-primary;
				}
			}

			.body-content {
				font-size: $f-sm;
				color: rgba(0, 0, 0, 0.7);
				padding: 20rpx 20rpx 40rpx 20rpx;

				.list-text {
					display: flex;
					align-items: center;
				}
			}
		}

		.popup-view {
			padding: 50rpx 40rpx 45rpx 40rpx;

			.popup-title {
				text-align: center;
				font-size: 36rpx;
			}

			.footer-btn {
				display: flex;

				/deep/.u-button {
					margin: 90rpx 20rpx 0 20rpx;
				}
			}

			.icon {
				margin-left: 45rpx;
				color: rgba(0, 0, 0, 0.6);
			}

			/deep/.u-dropdown__content__mask {
				background-color: rgba(0, 0, 0, 0);
			}

			.number-box {
				display: flex;
				align-items: center;
			}

			.bt {
				width: 50rpx;
				height: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				border-radius: 5rpx;
			}

			.bg {
				background-color: #EBECEE;
			}

			.bgg {
				background-color: #f7f8fa;
			}

			.input-sytle {
				width: 120rpx;
				margin: 0 10rpx;
			}
		}
	}
</style>
